import { useNamespace } from '@ibiz-template/vue3-util';
import { defineComponent, PropType, VNode, computed } from 'vue';
import { ISysImage } from '@ibiz/model-core';
import { IIcon } from '@ibiz-template/runtime';

export const IBizIcon = defineComponent({
  name: 'IBizIcon',
  props: {
    icon: {
      type: Object as PropType<ISysImage | IIcon>,
    },
    size: {
      type: String as PropType<'small' | 'medium' | 'large'>,
    },
    baseDir: {
      type: String,
      default: 'images',
    },
  },
  setup(props) {
    const ns = useNamespace('icon');
    const BaseUrl = `${ibiz.env.assetsUrl}/${props.baseDir}/`;

    function getContent(icon?: ISysImage): VNode | null {
      if (icon) {
        if (icon.cssClass) {
          if (icon.cssClass.indexOf('fa-') !== -1) {
            return <i class={[ns.b(), icon.cssClass]} />;
          }
          return <ion-icon class={ns.b()} name={icon.cssClass}></ion-icon>;
        }
        if (icon.imagePath) {
          if (icon.imagePath.endsWith('svg')) {
            if (icon.imagePath.startsWith('http')) {
              return <ion-icon class={ns.b()} src={icon.imagePath}></ion-icon>;
            }
            return (
              <ion-icon
                src={BaseUrl + icon.imagePath}
                class={ns.b()}
              ></ion-icon>
            );
          }
          if (icon.imagePath.startsWith('http')) {
            return <img class={ns.b()} src={icon.imagePath} />;
          }
          return <img class={ns.b()} src={BaseUrl + icon.imagePath} />;
        }
        if (icon.rawContent) {
          return <img class={ns.b()} src={icon.rawContent} />;
        }
      }
      return null;
    }

    const content = computed<VNode | null>(() => {
      return getContent(props.icon);
    });

    return (): VNode | null => content.value;
  },
});
